import axios from 'axios';
import config from './config';
import ZZToast from '@/utils/toast';
import router from '../../router';

// const ZZTOKENKEY = 'juhaohuan_platform_token';

const pending = [];
// const CancelToken = axios.CancelToken;
const removePending = (config) => {
  for (const p in pending) {
    if (pending.hasOwnProperty(p)) {
      const list = pending[p];
      if (list.url === config.url + '&request_type=' + config.method) {
        list.cancel();
        pending.splice(+p, 1);
      }
    }
  }
};

const service = axios.create(config);
// 添加请求拦截器
service.interceptors.request.use(
  config => {
    return config;
  },
  error => {
    return Promise.reject(error);
  }
);

// 返回状态判断(添加响应拦截器)
service.interceptors.response.use(
  res => {
    removePending(res.config);
    return res;
  },
  error => {
    return Promise.reject(error);
  }
);

/**
 * 封装了几个通用的请求函数
 */
export default async function ajax({
  url,
  params = null,
  data = null,
  hideLoading = false,
  method = 'GET'
}) {
  console.log(url);
  // const accessToken = localStorage.getItem(ZZTOKENKEY) || '';
  // params添加到url中
  if (hideLoading === false) {
    ZZToast.loading();
  }
  try {
    const result = await service({
      url,
      method,
      params,
      data
    });
    console.log('---------------------------1');
    console.log(result);
    console.log(result.data);
    const res = result.data;
    ZZToast.hide();
    if ((res && res.code === 200) || (result.status === 200)) {
      // 成功了
      return result.data;
    } else if (res.data && res.code === 401) {
      // 登录过期
      ZZToast.warn('登录过期');
      router.push('/login');
    } else {
      console.log(res);
      const msg = res.message || '请求失败';
      throw new Error(msg);
    }
  } catch (error) {
    ZZToast.hide();
    ZZToast.warn(error.message || '网络错误');
    throw error;
  }
}
